package com.application.viewmodel;

import android.content.Context;
import android.widget.Toast;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.application.bean.Student;
import com.application.util.MySQLiteOpenHelper;

import java.util.List;

public class SQLiteQueryViewModel extends ViewModel {
    public MutableLiveData<String> resultLiveData = new MutableLiveData<>();
    public MutableLiveData<String> numberLiveData = new MutableLiveData<>();
    private MySQLiteOpenHelper dbHelper;

    public void initDbHelper(Context context) {
        dbHelper = new MySQLiteOpenHelper(context);
    }

    public void queryByNumber(Context context) {
        String number = numberLiveData.getValue();
        if (number == null || number.isEmpty()) {
            Toast.makeText(context, "请输入学号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!number.matches("\\d+")) {
            Toast.makeText(context, "学号必须为数字", Toast.LENGTH_SHORT).show();
            return;
        }
        Student student = dbHelper.queryFromDbByNumber(number);
        if (student != null) {
            resultLiveData.setValue(
                    "姓名:" + student.getName() +
                            ",性别:" + student.getGender() +
                            ",学号:" + student.getNumber() +
                            ",分数:" + student.getScore()
            );
        } else {
            resultLiveData.setValue("未查询到该学生");
        }
    }

    public void queryAll(Context context) {
        List<Student> studentList = dbHelper.queryAllData();
        if (studentList != null) {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < studentList.size(); i++) {
                Student student = studentList.get(i);
                result.append(i + 1).append(": ")
                        .append("学号:").append(student.getNumber()).append(" ")
                        .append("姓名:").append(student.getName()).append(" ")
                        .append("性别:").append(student.getGender()).append(" ")
                        .append("分数:").append(student.getScore()).append("\n\n");
            }
            resultLiveData.setValue(result.toString());
        } else {
            resultLiveData.setValue("未查询到该学生");
        }
    }

}
